package com.boyaa.lxc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.boyaa.lxc.common.PCPU;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PokerActivity extends Activity {
	Button deal;
	Button showburst;
	Button setPhoto;
	ImageView[] imageView = new ImageView[12];
	TextView tip ;
	int [] cards = new int[7];
	int count = 0;
	private boolean pcpuFlag = true;
	PokerHands pokerHands ;
	private static BitmapFactory bf = new BitmapFactory();
	
	/*拍照的照片存储位置*/
	private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera");
	private File mCurrentPhotoFile;//照相机拍照得到的图片
	/*用来标识请求照相功能的Activity*/
	private static final int CAMERA_WITH_DATA = 3023;
	/**用来标识请求gallery的activity*/
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	


	
	public  Bitmap getPoker(int value){
		return bf.decodeResource( getResources(), CardValue.getCard(value));
	}
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initUI();
        pokerHands = new PokerHands();
        pokerHands.shuffle();
        
        Runtime rt = Runtime.getRuntime();
        rt.availableProcessors();
        
        new Thread(){

			@Override
			public void run() {
				while(pcpuFlag){
					SystemClock.sleep(1000);
					PCPU.pcpu();
				}

			}
        	
        }.start();
    }
    
   
    
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		pcpuFlag = false;
	}
	void initUI(){
    	deal = (Button) findViewById(R.id.deal);
    	showburst = (Button) findViewById(R.id.showburst);
    	setPhoto = (Button)findViewById(R.id.setPhoto);
    	tip = (TextView) findViewById(R.id.tip);
    	
    	imageView[0]= (ImageView) findViewById(R.id.image1);
    	imageView[1]= (ImageView) findViewById(R.id.image2);
    	imageView[2]= (ImageView) findViewById(R.id.image3);
    	imageView[3]= (ImageView) findViewById(R.id.image4);
    	imageView[4]= (ImageView) findViewById(R.id.image5);
    	imageView[5]= (ImageView) findViewById(R.id.image6);
    	imageView[6]= (ImageView) findViewById(R.id.image7);
    	
    	/**
    	 * 自己的五张牌
    	 */
    	imageView[7]= (ImageView) findViewById(R.id.image8);
    	imageView[8]= (ImageView) findViewById(R.id.image9);
    	imageView[9]= (ImageView) findViewById(R.id.image10);
    	imageView[10]= (ImageView) findViewById(R.id.image11);
    	imageView[11]= (ImageView) findViewById(R.id.image12);
    	
    }
    
    public void setPhoto(View view){
    	doPickPhotoAction();
    	PCPU.pcpu();
    }
    public void showBurst(View view){
    	showToast(""+5000);
//    	getCPUinfo();
//    	getMemeryInfo();
    	PCPU.pcpu();
    }
    
    /**
     * 发牌
     * @param view
     */
    public void dealCard(View view){
    	if(count == 0){//发手牌
    		cards[0] = pokerHands.dealPoker();
    		cards[1] = pokerHands.dealPoker();
    		
    		imageView[0].setImageBitmap(getPoker(cards[0]));
    		imageView[1].setImageBitmap(getPoker(cards[1]));
    		count++;
    	}else if(count == 1){//发三张
    		for(int i=2;i<5;i++){
    			cards[i] = pokerHands.dealPoker();
    			imageView[i].setImageBitmap(getPoker(cards[i]));
    		}
    		count++;
    		check(cards);
    	}else if(count == 2){
			cards[5] = pokerHands.dealPoker();
			imageView[5].setImageBitmap(getPoker(cards[5]));
			count++;
			check(cards);
    	}else if(count == 3){
			cards[6] = pokerHands.dealPoker();
			imageView[6].setImageBitmap(getPoker(cards[6]));
//    		test();
			count++;
			check(cards);
    	}else{
    		count=0;
    		for(int i=0;i<12;i++){
    			if(i<7)
    				cards[i]=0;
    			imageView[i].setImageBitmap(null);
    		}
    		 pokerHands.shuffle();
    	}
    	PCPU.pcpu();
    	//getMemeryInfo();
    }
    
    public void check(int[] cards){
    	String text = pokerHands.checkHandsType(cards);
    	tip.setText(text);
    	Toast.makeText(PokerActivity.this, text, Toast.LENGTH_SHORT).show();
    	int [] myCard = pokerHands.getMyCards();
    	for(int i=7;i<12;i++){
    		imageView[i].setImageBitmap(getPoker(myCard[i-7]));
    	}
    }
    
    public void test(){
    	cards = new int[]{
    		0x0104,0x0203,0x0302,0x010E,0x0105
    	};
    	for(int i = 0;i<cards.length;i++){
    		imageView[i].setImageBitmap(getPoker(cards[i]));
    	}
    }
    
    
    /**
     * 爆炸试动画
     * @param tips
     */
    public void showToast(String tips){
    	LayoutInflater layoutInflater = LayoutInflater.from(this);
    	View view = layoutInflater.inflate(R.layout.burst_toast, null);
    	ImageView burst = (ImageView) view.findViewById(R.id.busrt);
    	TextView tx = (TextView) view.findViewById(R.id.money);
    	tx.setText(tips);
    	
    	ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f,1.0f,0.0f,1.0f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
    	scaleAnimation.setDuration(2000);
    	scaleAnimation.setInterpolator(new AccelerateInterpolator());
    	tx.startAnimation(scaleAnimation);
    	
    	Animation animation = AnimationUtils.loadAnimation(this, R.anim.burst);
    	burst.startAnimation(animation);
    	Toast toast = new Toast(this);
    	toast.setView(view);
    	toast.setDuration(Toast.LENGTH_LONG);
    	toast.show();
    }
    
    

    
    public String getMemeryInfo(){
    	StringBuilder sb = new StringBuilder();
    	ProcessBuilder cmd;
    	String [] args = {"/system/bin/cat","/proc/meminfo"};
    	cmd = new ProcessBuilder(args);
    	InputStream in = null;
    	try {
			Process process = cmd.start();
			in = process.getInputStream();
			byte[] re = new byte[1*1024];
			while(in.read(re) != -1){
				sb.append(new String(re));
			}
			if(in != null){
				in.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    	Log.d("DEBUG","memery=="+sb.toString());
    	return sb.toString();
    }
    
    
    
    private void doPickPhotoAction(){
    	Log.d("DEBUG","doPickPhotoAction");
    	Context context = PokerActivity.this;
    	
    	//Wrap our context to inflate list items using correct theme
    	final Context dialogContext = new ContextThemeWrapper(context,android.R.style.Theme_Light);
    	String cancel = "返回";
    	String[] choices;
    	choices = new String[2];
    	choices[0] = "拍照";
    	choices[1] = "从相册中选择";
    	ListAdapter adapter = new ArrayAdapter<String>(dialogContext,android.R.layout.simple_list_item_1,choices);
    	AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
    	
    	builder.setTitle("照片设置");
    	builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				switch(which){
				case 0:
					doTakePhoto();
					break;
				case 1:
					doPickPhotoFromGallery();//从相册中去获取
					break;
				}
			}
		});
    	builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	
    	builder.create().show();
    	
    }

	/**
     * 拍照获取图片 
     */
	protected void doTakePhoto() {
		//Launch camera to take photo for selected contact
		String status = Environment.getExternalStorageState();
		if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡的读写权限
			PHOTO_DIR.mkdirs();//创建照片的存储目录
			mCurrentPhotoFile = new File(PHOTO_DIR,getPhotoFileName());//给新照片文件命名
			Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent,CAMERA_WITH_DATA);
		}else{
			showToast("没有SD卡");
		}
	}
	
	private Intent getTakePickIntent(File mCurrentPhotoFile) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
		return intent;
		
	}
	/**
	 * 用当前时间给取得的图片命名
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");//命名要特别注意
		return dateFormat.format(date)+".jpg";
	}
	
	/**
	 * 请求Gallery程序
	 */
    protected void doPickPhotoFromGallery() {
    	Intent intent = getPhotoPickIntent();
    	startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}
	private Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT,null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
//		intent.putExtra("aspectX", 1);
//		intent.putExtra("aspectY", 1);
//		intent.putExtra("outputX", 80);
//		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	/**
	 * 因为调用了Camera和Gally所以要判断他们各自的返回情况，
	 * 他们启动时是这样的startActivityForResult
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode != RESULT_OK)
			return;
		switch(requestCode){
		case PHOTO_PICKED_WITH_DATA:
			Bitmap photo = data.getParcelableExtra("data");
			int width = photo.getWidth();
			int height = photo.getHeight();
			Log.d("DEBUG","widht="+width+" height="+height);
			//BitmapFactory.Options options = new BitmapFactory.Options();
			
			
			File file = new File(PHOTO_DIR,getPhotoFileName());
			Log.d("DEBUG","fileName = "+ file.getName());
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(fos != null);
			photo.compress(Bitmap.CompressFormat.PNG, 100, fos);
			imageView[0].setImageBitmap(photo);
			break;
		case CAMERA_WITH_DATA:
			doCropPhoto(mCurrentPhotoFile);
			break;
		
		}
	}
	
	/**
	 * 启动gallery去剪辑这个照片
	 * @param file
	 */
	private void doCropPhoto(File file) {
		final Intent intent = getCropImageIntent(Uri.fromFile(file));
		startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}
	
	/**
	 * Constructs an intent for image cropping.
	 * 调用图片剪辑程序 
	 * @param fromFile
	 * @return
	 */
	  public static Intent getCropImageIntent(Uri photoUri) {  
	      Intent intent = new Intent("com.android.camera.action.CROP");  
	      intent.setDataAndType(photoUri, "image/*");  
	      intent.putExtra("crop", "true");  
	      intent.putExtra("aspectX", 1);  
	      intent.putExtra("aspectY", 1);  
	      intent.putExtra("outputX", 80);  
	      intent.putExtra("outputY", 80);  
	      intent.putExtra("return-data", true);
		  Log.d("DEBUG","getCropImageIntent");
	      return intent;  
	  }  
	
	
	
    
    
    
}